const path = require('path')
const args = require('minimist')(process.argv.slice(2))
const packagesDir = path.resolve(__dirname, '../packages')
const distDir = path.resolve(__dirname, '../dist')
const { collectPackages, runParallel } = require('./utils')
const vueCli = require('./vue-cli')
let packages = collectPackages(packagesDir)

const release = function(package) {
  const pkg = package.value
  const buildOptions = pkg.buildOptions
  if (buildOptions && buildOptions.target) {
    const appRootDir = package.path
    const targetName = buildOptions.name ? buildOptions.name : package.directory

    const outputDir = buildOptions.outputDir ? buildOptions.outputDir : path.resolve(distDir, targetName)
    switch (buildOptions.target) {
      case 'web': // 构建为网站
        vueCli.exec(appRootDir, ['build', '--dest', outputDir])
        break
      case 'plugin':
        vueCli.exec(appRootDir, ['build', '--dest', outputDir, '--target', 'lib', '--name', targetName, './src/main.ts']) // , '--target', 'lib', './src/index.ts'
        break
      default:
        break
    }
  }
}

// 若提供了only选项仅仅编译only选项的包
const only = args.only || ''
packages = packages.filter(package => {
  const buildOptions = package.value.buildOptions
  if (!buildOptions) return false
  if (!buildOptions.target) return false
  const targetName = buildOptions.name ? buildOptions.name : package.directory
  if (only) {
    if (only == targetName) return true
    else return false
  }
  return true
})

// 根据操作系统的核心数量并行发包
runParallel(require('os').cpus().length, packages, release)
